<?php

namespace Sisesporte\View\Helper;

use Zend\View\Helper\AbstractHelper;

class FlashMessenger extends AbstractHelper {

    /**
     * @var Zend_Controller_Action_Helper_FlashMessenger
     */
    private $_flashMessenger = null;

    /**
     * Display Flash Messages.
     *
     * @param  string $key Message level for string messages
     * @param  string $template Format string for message output
     * @return string Flash messages formatted for output
     */
    public function FlashMessenger($key = 'warning', $template = '<div class="alert alert-%s">%s</div>') {
        $flashMessenger = $this->_getFlashMessenger();

        $rand = rand(11111, 99999);
        $template = '<div id="' . $rand . '" class="sticky border-top-right st-%s" style="display: block;">';
        $template .= '<span title="Close" rel="' . $rand . '" class="close st-close">×</span>';
        $template .= '<div rel="' . $rand . '" class="sticky-note">%s</div>';
        $template .= '</div>';

        //get messages from previous requests
        $messages = $flashMessenger->getMessages();

        //add any messages from this request
        if ($flashMessenger->hasCurrentMessages()) {
            $messages = array_merge(
                    $messages, $flashMessenger->getCurrentMessages()
            );
            //we don't need to display them twice.
            $flashMessenger->clearCurrentMessages();
        }

        //initialise return string
        $output = '<div class="sticky-queue top-right" style="width: auto;">';

        //process messages
        foreach ($messages as $message) {
            if (is_array($message)) {
                list($key, $message) = each($message);
            }
            $output .= sprintf($template, $key, $message);
        }
        return $output . '</div>';
    }

    /**
     * Lazily fetches FlashMessenger Instance.
     *
     * @return Zend_Controller_Action_Helper_FlashMessenger
     */
    public function _getFlashMessenger() {
        if (null === $this->_flashMessenger) {
            $this->_flashMessenger =
                    Zend_Controller_Action_HelperBroker::getStaticHelper(
                            'FlashMessenger');
        }
        return $this->_flashMessenger;
    }

}